package com.vipsoft.locker.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.vipsoft.base.core.ApiResult;
import com.vipsoft.base.entity.wechat.MemberInfo;
import com.vipsoft.locker.service.IMemberService;
import com.vipsoft.base.entity.locker.vo.UserInfo;
import com.vipsoft.base.entity.locker.vo.WxLoginInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/auth")
public class AuthController {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private WxMaService wxService;

    @Autowired
    IMemberService memberService;


//    @PostMapping("/login")
//    public ApiResult login(String code, String encryptedData,String iv, HttpServletRequest request, HttpServletResponse response) {
//        // 做跨域处理
//        response.setContentType("text/html;charset=utf-8");
//        response.setHeader("Access-Control-Allow-Origin", "*");
//        // 返回参数
//        Map<String, Object> datas = new HashMap<String, Object>();
//        // 微信对接参数
//        Map<String, String> param = new HashMap<String, String>();
//        //自己小程序的id
//        param.put("appid", "自己小程序的appid");
//        param.put("secret", "微信返回的小程序校验码");
//        if (code != null && code.trim().length() > 0)
//            param.put("js_code", code);
//        param.put("grant_type", "authorization_code");
//        String result = HttpClientUtil.doGet(
//                "https://api.weixin.qq.com/sns/jscode2session", param);
//        byte[] dataByte = Base64.decode(encryptedData);
//        JSONObject userJson = JSONObject.parseObject(result);
//        byte[] keyByte = Base64.decode(userJson.getString("session_key"));
//        byte[] ivByte = Base64.decode(iv);
//        try {
//            int base = 16;
//            if (keyByte.length % base != 0) {
//                int groups = keyByte.length / base
//                        + (keyByte.length % base != 0 ? 1 : 0);
//                byte[] temp = new byte[groups * base];
//                Arrays.fill(temp, (byte) 0);
//                System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
//                keyByte = temp;
//            }
//            Security.addProvider(new BouncyCastleProvider());
//            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
//            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
//            AlgorithmParameters parameters = AlgorithmParameters
//                    .getInstance("AES");
//            parameters.init(new IvParameterSpec(ivByte));
//            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
//            byte[] resultByte = cipher.doFinal(dataByte);
//            if (null != resultByte && resultByte.length > 0) {
//                String dec = new String(resultByte, "UTF-8");
//                System.out.println(dec);
//                // 解析出用户数据
//                Map<String, Object> wxinfo = (Map) JSON.parse(dec);
//                // ===解析出用户openid根据其查询用户数据，判断用户是否是新用户，是的话，将用户信息存到数据库；不是的话，更新最新登录时间
//                // 3.接收微信接口服务 获取返回的参数
//                String openId = wxinfo.get("openId").toString();
//                System.out.println("openId" + openId + "=====");
//                // 查询
//                PageModel page = new PageModel();
//                HashMap<String, Object> condition = new HashMap<>();
//                condition.put("openid", openId);
//                condition.put("type", "wxprogram");
//                page.setCondition(condition);
//                List<UserChannel> userChannels = userChannelService
//                        .queryByPage(page);
//                UserChannel userChannel = new UserChannel();
//                UserInfo userInfo = new UserInfo();
//                // 如果用户为空，则存库
//                if (userChannels.size() == 0) {
//                    // 先存入登录渠道库
//                    userChannel.setId(UUID.randomUUID().toString()
//                            .replace("-", ""));
//                    String userId = UUID.randomUUID().toString()
//                            .replace("-", "");
//                    userChannel.setUserId(userId);
//                    userChannel.setType("wxprogram");
//                    userChannel.setContent(dec);
//                    userChannelService.insert(userChannel);
//                    // 存入用户详情库
//                    userInfo.setId(userId);
//                    userInfo.setPhoto(wxinfo.get("avatarUrl").toString());
//                    userInfo.setGender(0);
//                    userInfo.setCreateTime(new Date());
//                    userInfo.setLastTime(new Date());
//                    userInfo.setStatus(0);
//                    userInfo.setType(1);
//                    userInfo.setNickname(wxinfo.get("nickName").toString());
//                    userInfoService.insert(userInfo);
//                } else {
//                    // 已存在，更新用户登录时间
//                    userInfo = userInfoService.queryById(userChannels.get(0).getUserId());
//                    userInfo.setPhoto(wxinfo.get("avatarUrl").toString());
//                    userInfo.setLastTime(new Date());
//                    userInfoService.update(userInfo);
//                }
//                datas.put(RESPONSE_DATA, userInfo);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        datas.put(RESPONSE_RESULT, Constants.SUCCESS);
//        return new ApiResult(datas);
//    }


    /**
     * 微信登录
     *
     * @param wxLoginInfo 请求内容，{ code: xxx, userInfo: xxx }
     * @param request     请求对象
     * @return 登录结果
     */
    @PostMapping("login")
    public ApiResult login(@RequestBody WxLoginInfo wxLoginInfo, HttpServletRequest request) {
        String code = wxLoginInfo.getCode();
        UserInfo userInfo = wxLoginInfo.getUserInfo();
        if (code == null || userInfo == null) {
            return new ApiResult(6001, "传入参数无效");
        }

        String sessionKey = null;
        String openId = null;
        String unionId = null;
        try {
            WxMaJscode2SessionResult result = this.wxService.getUserService().getSessionInfo(code);
            sessionKey = result.getSessionKey();
            openId = result.getOpenid();
            unionId = result.getUnionid();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage(),e);
        }

        LambdaQueryWrapper<MemberInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MemberInfo::getOpenId,openId);
        MemberInfo memberInfo = memberService.getOne(queryWrapper,false);
        if (memberInfo == null) {
            memberInfo = new MemberInfo();
            memberInfo.setOpenId(openId);
            memberInfo.setNickName(userInfo.getNickName());
            memberInfo.setAvatarUrl(userInfo.getAvatarUrl());
            memberInfo.setGender(String.valueOf(userInfo.getGender()));
            memberInfo.setLastTime(new Date());
            memberService.save(memberInfo);
        }
//        LitemallUser user = userService.queryByUnionId(unionId);
//        if(user==null){
//            user = userService.queryByOid(openId);
//        }
//        if (user == null) {
//            user = new LitemallUser();
//            user.setUsername(openId);
//            user.setPassword(openId);
//            user.setWeixinOpenid(openId);
//            user.setWeixinUnionid(unionId);
//            user.setAvatar(userInfo.getAvatarUrl());
//            user.setNickname(userInfo.getNickName());
//            user.setGender(userInfo.getGender());
//            user.setUserLevel((byte) 0);
//            user.setStatus((byte) 0);
//            user.setLastLoginTime(LocalDateTime.now());
//            user.setLastLoginIp(IpUtil.getIpAddr(request));
//            user.setSessionKey(sessionKey);
//            user.setAppId(this.wxService.getWxMaConfig().getAppid());
//            userService.add(user);
//
//        } else {
//            user.setWeixinUnionid(unionId);
//            user.setLastLoginTime(LocalDateTime.now());
//            user.setLastLoginIp(IpUtil.getIpAddr(request));
//            user.setSessionKey(sessionKey);
//            if (userService.updateById(user) == 0) {
//                return ResponseUtil.updatedDataFailed();
//            }
//        }

        // token
//        String token = UserTokenManager.generateToken(user.getId());

        Map<Object, Object> result = new HashMap<Object, Object>();
        result.put("token", memberInfo.getId()); //请求接口用
        result.put("userInfo", memberInfo);
        return new ApiResult(result);
    }


}
